/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import MongoInterface.MongoDB;
import SQLParser.Parser;
import SQLTranslator.SQLToMongo;
import SQLTranslator.TranslatorThread;
import com.mongodb.client.MongoIterable;
import javax.swing.JOptionPane;

/**
 *
 * @author Lenovo
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    SQLToMongo translator;
    Parser p;
    public Main() {
        initComponents();
        this.translator = new SQLToMongo();
        this.p = Parser.getSQLParser();
        //refreshListDB();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    textInputQuery = new javax.swing.JTextArea();
    buttExecute = new javax.swing.JButton();
    butClear = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    textResultSet = new javax.swing.JTextArea();
    jLabel1 = new javax.swing.JLabel();
    buttValid = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    labelValid = new javax.swing.JLabel();
    comboDatabases = new javax.swing.JComboBox<>();
    butRefreshDB = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    butSetDB = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    menuFile = new javax.swing.JMenu();
    menuHelp = new javax.swing.JMenu();
    menuAbout = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("SQLToMongo");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        formWindowClosing(evt);
      }
    });

    textInputQuery.setColumns(20);
    textInputQuery.setRows(5);
    jScrollPane1.setViewportView(textInputQuery);

    buttExecute.setText("Execute");
    buttExecute.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttExecuteActionPerformed(evt);
      }
    });

    butClear.setText("Clear");
    butClear.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        butClearActionPerformed(evt);
      }
    });

    textResultSet.setColumns(20);
    textResultSet.setRows(5);
    jScrollPane2.setViewportView(textResultSet);

    jLabel1.setText("Result Set");

    buttValid.setText("Cek Validitas");
    buttValid.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttValidActionPerformed(evt);
      }
    });

    jLabel2.setText("Input Query SQL");

    labelValid.setText("VALID");

    comboDatabases.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--choose DB--" }));

    butRefreshDB.setText("Refresh DB");
    butRefreshDB.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        butRefreshDBActionPerformed(evt);
      }
    });

    jLabel3.setText("Database: ");

    butSetDB.setText("Set DB");
    butSetDB.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        butSetDBActionPerformed(evt);
      }
    });

    menuFile.setText("File");
    jMenuBar1.add(menuFile);

    menuHelp.setText("Help");
    menuHelp.setToolTipText("");
    jMenuBar1.add(menuHelp);

    menuAbout.setText("About");
    jMenuBar1.add(menuAbout);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                  .addComponent(buttExecute, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(butClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(buttValid, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
              .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(labelValid))))
          .addComponent(jLabel1)
          .addComponent(jLabel3)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(comboDatabases, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGap(24, 24, 24)
            .addComponent(butRefreshDB, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(butSetDB)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jLabel3)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(comboDatabases, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(butRefreshDB)
          .addComponent(butSetDB))
        .addGap(18, 18, 18)
        .addComponent(jLabel2)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(buttExecute)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(buttValid)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(butClear)
            .addGap(34, 34, 34)
            .addComponent(labelValid)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jLabel1)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void buttExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttExecuteActionPerformed

      boolean valid = setValid(isQueryValid(textInputQuery.getText()));
        if(valid){
          textResultSet.setText("");
          Thread t = new Thread(new TranslatorThread(this, p.getTokens()));
          t.start();
        }
    }//GEN-LAST:event_buttExecuteActionPerformed

    private void buttValidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttValidActionPerformed
        setValid(isQueryValid(textInputQuery.getText()));
    }//GEN-LAST:event_buttValidActionPerformed

    private void butClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butClearActionPerformed
        textInputQuery.setText("");
    }//GEN-LAST:event_butClearActionPerformed

  private void butRefreshDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butRefreshDBActionPerformed
    clearListDB();
    refreshListDB();
  }//GEN-LAST:event_butRefreshDBActionPerformed

  private void butSetDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSetDBActionPerformed
    setDB();
  }//GEN-LAST:event_butSetDBActionPerformed

  private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    MongoDB.getDatabaseConnection().close();
  }//GEN-LAST:event_formWindowClosing

  private void setDB(){
    if (comboDatabases.getSelectedIndex()>0){
      MongoDB m = MongoDB.getDatabaseConnection();
      m.setDatabase(comboDatabases.getSelectedItem().toString());
    }
    else
      JOptionPane.showMessageDialog(this, "Pilih Database yang valid","Error!", JOptionPane.ERROR_MESSAGE);
  }
  private void clearListDB(){
    while(comboDatabases.getItemCount()>1) comboDatabases.removeItemAt(1);
  }
  public boolean setValid(boolean valid){
      String text;
      if(valid) text="VALID";
      else text = "TIDAK VALID";
      labelValid.setText(text);
      return valid;
  }
  private boolean isQueryValid(String query){
      if(query.length()>0){
          return p.parse(query);
      }
      return false;
  }
    
    public void appendResult(String r){
        textResultSet.append(r+"\n");   
    }
    private void refreshListDB(){
      MongoDB m = MongoDB.getDatabaseConnection();
      MongoIterable<String> databases = m.getDatabaseList();
      for(String s : databases){
        comboDatabases.addItem(s);
      }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton butClear;
  private javax.swing.JButton butRefreshDB;
  private javax.swing.JButton butSetDB;
  private javax.swing.JButton buttExecute;
  private javax.swing.JButton buttValid;
  private javax.swing.JComboBox<String> comboDatabases;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JMenuBar jMenuBar1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JLabel labelValid;
  private javax.swing.JMenu menuAbout;
  private javax.swing.JMenu menuFile;
  private javax.swing.JMenu menuHelp;
  private javax.swing.JTextArea textInputQuery;
  private javax.swing.JTextArea textResultSet;
  // End of variables declaration//GEN-END:variables
}
